package com.lcw.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * swagger api经过zuul后，api url中会多一个/tianmi。对此情况进行处理
 */
@Component
public class SwaggerRedirectFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(SwaggerRedirectFilter.class);

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //filterOrder：过滤的顺序
    @Override
    public int filterOrder() {
        return 1;
//        return FilterConstants.SEND_FORWARD_FILTER_ORDER;
    }

    /* (non-Javadoc)filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
                    pre：路由之前
                    routing：路由之时
                    post： 路由之后
                    error：发送错误调用
     */
    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String url = request.getRequestURL().toString();
        String queryParams = request.getQueryString();
        log.info("收到的url: {}, queryParams:{}", url, queryParams);
        if (shouldBeRedirected(url)) {
            String redirectUrl = generateRedirectUrl(url, queryParams);
            sendRedirect(ctx.getResponse(), redirectUrl);

        }
        return null;
    }

    /**
     * 重定向
     * @param response
     * @param redirectUrl
     */
    private void sendRedirect(HttpServletResponse response, String redirectUrl) {
        log.info("开始重定向了");
        try {
            response.setHeader(HttpHeaders.LOCATION, redirectUrl);
            response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
            response.flushBuffer();
        } catch (IOException ex) {
            log.error("Could not redirect to: " + redirectUrl, ex);
        }
    }
    /**
     * 是否需要重定向
     * @param url
     * @return
     */
    private boolean shouldBeRedirected(String url) {
        if (StringUtils.isNotBlank(url) && url.indexOf("/tianmi/tianmi") >= 0) {
            return true;
        }
    	return false;
    }


    /**
     * 重定向后的地址
     * @param url
     * @param queryParams
     * @return
     */
    private String generateRedirectUrl(String url, String queryParams) {
        url = url.replace("/tianmi/tianmi", "/tianmi");
        url = url.replace("http://tianmi.dahe.cn", "https://tianmi.dahe.cn");
        String currentUrl = url + (queryParams == null ? "" : ("?" + queryParams));
        log.info("转换后: {}", currentUrl);
        return currentUrl;
    }
}